//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Localization;
namespace DotNetNuke.Modules.Admin.Modules
{
	partial class ViewSource : Entities.Modules.PortalModuleBase
	{
		protected bool CanEditSource
		{
			get { return Request.IsLocal; }
		}
		protected int ModuleControlId
		{
			get
			{
				int _ModuleControlId = Null.NullInteger;
				if ((Request.QueryString["ctlid"] != null))
				{
					_ModuleControlId = Int32.Parse(Request.QueryString["ctlid"]);
				}
				return _ModuleControlId;
			}
		}
		private void BindFiles(string controlSrc)
		{
			cboFile.Items.Clear();
			cboFile.Items.Add(new ListItem(Localization.GetString("None_Specified"), "None"));
			cboFile.Items.Add(new ListItem("User Control", "UserControl"));
			string srcPhysicalPath = Server.MapPath(controlSrc);
			if (File.Exists(srcPhysicalPath + ".vb") || File.Exists(srcPhysicalPath + ".cs"))
			{
				cboFile.Items.Add(new ListItem("Code File", "CodeFile"));
			}
			string fileName = Path.GetFileName(srcPhysicalPath);
			string folder = Path.GetDirectoryName(srcPhysicalPath);
			if (File.Exists(folder + "\\App_LocalResources\\" + fileName + ".resx"))
			{
				cboFile.Items.Add(new ListItem("Resource File", "ResourceFile"));
			}
		}
		private string GetSourceFileName(string controlSrc)
		{
			string srcPhysicalPath = Server.MapPath(controlSrc);
			string srcFile = Null.NullString;
			switch (cboFile.SelectedValue)
			{
				case "UserControl":
					srcFile = srcPhysicalPath;
					break;
				case "CodeFile":
					if (File.Exists(srcPhysicalPath + ".vb"))
					{
						srcFile = srcPhysicalPath + ".vb";
					}
					else if (File.Exists(srcPhysicalPath + ".cs"))
					{
						srcFile = srcPhysicalPath + ".cs";
					}
					break;
				case "ResourceFile":
					string fileName = Path.GetFileName(srcPhysicalPath);
					string folder = Path.GetDirectoryName(srcPhysicalPath);
					srcFile = folder + "\\App_LocalResources\\" + fileName + ".resx";
					break;
			}
			return srcFile;
		}
		private void DisplayFile()
		{
			ModuleControlInfo objModuleControl = ModuleControlController.GetModuleControl(ModuleControlId);
			if (objModuleControl != null)
			{
				string srcVirtualPath = objModuleControl.ControlSrc;
				string srcFile = Null.NullString;
				bool displaySource = cboFile.SelectedValue != "None";
				if (displaySource)
				{
					srcFile = GetSourceFileName(srcVirtualPath);
					lblSourceFile.Text = string.Format(Localization.GetString("SourceFile", this.LocalResourceFile), srcFile);
					StreamReader objStreamReader;
					objStreamReader = File.OpenText(srcFile);
					txtSource.Text = objStreamReader.ReadToEnd();
					objStreamReader.Close();
				}
				lblSourceFile.Visible = displaySource;
				trSource.Visible = displaySource;
			}
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cboFile.SelectedIndexChanged += new EventHandler(cboFile_SelectedIndexChanged);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);
			cmdUpdate.Click += new EventHandler(cmdUpdate_Click);

			if (Page.IsPostBack == false)
			{
				ModuleControlInfo objModuleControl = ModuleControlController.GetModuleControl(ModuleControlId);
				if (objModuleControl != null)
				{
					BindFiles(objModuleControl.ControlSrc);
				}
				if (Request.UrlReferrer != null)
				{
					ViewState["UrlReferrer"] = Convert.ToString(Request.UrlReferrer);
				}
				else
				{
					ViewState["UrlReferrer"] = "";
				}
			}
			cmdUpdate.Visible = CanEditSource;
			txtSource.Enabled = CanEditSource;

		}
		protected void cboFile_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			DisplayFile();
		}
		private void cmdCancel_Click(System.Object sender, System.EventArgs e)
		{
			try
			{
				Response.Redirect(Common.Globals.NavigateURL(), true);
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdUpdate_Click(object sender, System.EventArgs e)
		{
			try {
				 if (cboFile.SelectedValue == "None")
				 {
                    //No file type selected
					 Skin.AddModuleMessage(this, Localization.GetString("NoFileTypeSelected", this.LocalResourceFile), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				 }
				 else
				 {
				ModuleControlInfo objModuleControl = ModuleControlController.GetModuleControl(ModuleControlId);
				if (objModuleControl != null) {
					string srcVirtualPath = objModuleControl.ControlSrc;
					string srcPhysicalPath = GetSourceFileName(srcVirtualPath);
					if (File.Exists(srcPhysicalPath)) {
						File.SetAttributes(srcPhysicalPath, FileAttributes.Normal);
						StreamWriter objStream;
						objStream = File.CreateText(srcPhysicalPath);
						objStream.WriteLine(txtSource.Text);
						objStream.Close();
					}
				}
				Response.Redirect(Common.Globals.NavigateURL(), true);
				 }
			} catch (Exception exc) {
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
	}
}
